import { Icon } from 'antd';
import ProLayout from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import { Link, NavLink, router } from 'umi';
import { connect } from 'dva';

import RightContent from '@/components/GlobalHeader/RightContent';
import logo from '@/assets/onelogo.png';
import horn from '@/assets/lb.svg';
import number from '@/assets/rs.svg';
import styles from './BasicLayout.less';
import { useRequest } from '@umijs/hooks';
import { getUserDetail, getMsgList, getUserBindRoom } from '@/services';

import AuthComponent from '@/components/Authorized/AuthComponent';

/**
 * use Authorized check all menu item
 */
const menuDataRender = menuList => {
  return menuList && menuList.length && menuList.map(item => ({
    ...item,
    children: item.children ? menuDataRender(item.children) : [],
  }));
};
const scale2 = { textAlign: 'center' };
const BasicLayout = props => {
  const { children, settings, appMenus = [], favoriteMenus = [] } = props;
  const menuLayout = (hasChildrenPath) => hasChildrenPath.length && hasChildrenPath.filter(childrenPath => (location.href.indexOf(childrenPath.path) + 1)).length;

  // 在接口返回的路由表中，过滤掉普通航班监控航延补偿，不正常航班监控航延补偿，服务补偿子平台赔偿单表单
  let tempAppMenus = JSON.parse(JSON.stringify(appMenus));
  for (let menuItme of tempAppMenus) {
    if (menuItme.path === '/usualMonitor') { //普通航班监控
      menuItme.children =  menuItme.children.filter(item => item.path !== '/usualMonitor/usualMonitor/AuditDetail');
    }
    if (menuItme.path === '/unusualMonitor') { // 不正常航班监控
      menuItme.children =  menuItme.children.filter(item => item.path !== '/usualMonitor/usualMonitor/AuditDetail');
    }
    if (menuItme.path === '/compensation/indemnitySheet') { // 服务补偿子平台
      menuItme.children =  menuItme.children.filter(item => item.path !== '/compensation/indemnityForm' && item.path !== '/compensation/CompensationAudit/AuditDetail' && item.path !== '/compensation/luggageLndemnifyDetails');
    }
  };
  const defaultMenus = [...tempAppMenus];

  const userId = localStorage.getItem('id');
  const { run: getUser, data: currentUser = {}, currentUserLoading } = useRequest(() =>
    getUserDetail({ userId: userId }),{
    onSuccess: data => {
        getUserBindRoomFun()
        sessionStorage.setItem('airport', data.airport)
    },
    onError: err => {
      getUserBindRoomFun()
    },
  }
  );
  //当前登录用户的绑厅信息
  const { run: getUserBindRoomFun } = useRequest(getUserBindRoom, {
    onSuccess: data => {
      localStorage.setItem('userBindRoomId', data?.length > 0 ? data[0].id : '');
    },
  });
  // 获取未读消息
    const { loading, data, run } = useRequest(() =>
    getMsgList({
      page: 1, msgState: 1, size:3, msgType: ''
    }), {
    pollingInterval: 30000,
    initialData: [],
    onSuccess () {
    },
  });
  const toMsg = () => {

    router.push('/compensation/messageCenter')
  }
  return (
    <ProLayout
      className={styles.container}
      disableContentMargin
      menuRender={(a, defaultMenu) => ({
        ...defaultMenu,
        props: { ...defaultMenu.props, selectedKeys: [] },
      })}
      onCollapse={() => { }}
      collapsedButtonRender={() => (
        <div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'flex-start', height: '64px' }}>
          <div style={{ paddingRight: '15px' }}>
            <img src={`${logo}`} alt="" />
          </div>
          <p style={{ fontSize: 20, fontWeight: 600, color: '#1E385A' }}> 旅客服务信息系统</p>

          <AuthComponent authCode="message.index.show">
            <p style={{ fontSize: '14px', paddingLeft: '45px' }}>
              <img src={`${horn}`} alt="" style={{ paddingRight: '5px' }} />
              未读消息<span style={{ color: '#E13B3B', padding: '0 8px' }} onClick={toMsg}>{(data && data.pagination || {}).total ?? 0}</span>条
            </p>
          </AuthComponent>
        </div>
      )}
      collapsed={false}
      rightContentRender={() => (
        <RightContent
          currentUser={currentUser}
          currentUserLoading={currentUserLoading}
          getUser={getUser}
        />
      )}
      logo={logo}
      menuHeaderRender={(logoDom, titleDom) => (
        <Link to="/">
          {logoDom}
          {titleDom}
        </Link>
      )}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.children || !menuItemProps.path) {
          return <div style={scale2}>{defaultDom}</div>;
        } else {
          if (menuItemProps.isUrl) {
            return <a href={menuItemProps.path} target="_blank">{menuItemProps.name}</ a>
          } else {
            return <NavLink to={menuItemProps.path} activeStyle={{ color: '#E13B3B', borderRight: '3px solid #E13B3B' }}>{defaultDom}</NavLink>;
          }
        }
      }}
      menuDataRender={() => defaultMenus}
      subMenuItemRender={(item, defaultDom) => {
        return <div className={`${item.className} ${menuLayout(item.children) ? 'ant-menu-submenu-router-active' : ''}`} style={menuLayout(item.children) ? { width: '350px', color: 'white', background: '#E13B3B', marginLeft: '-50px', paddingLeft: '50px' } : {}} >{defaultDom}</div>
      }}
      {...props}
      {...settings}
    >
      {children}
    </ProLayout>
  );
};

export default connect(({ global, settings }) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
